import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 设定请求key
    config.headers['requestKey'] = getRequestKey()
    // 设定请求traceId
    config.headers['TRACE_ID'] = getTraceId()

    if (store.getters.token) {
      // 设定token
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log('请求后端接口数据', res)

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        // 操作失败 账号错误
        message: dealMessage(res.message) || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      console.log('操作失败，阻断操作')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // console.log('接口响应数据: ', JSON.stringify(res))
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * 处理报错信息
 * @param msg 报错信息
 */
function dealMessage(msg) {
  console.log('打印日志', msg)
  if (msg == null) {
    return ''
  } else {
    return msg.split(' ')[1]
  }
}

/**
 * 获取请求key防止水平越权
 * @returns 请求key
 */
function getRequestKey() {
  const now = new Date()
  return Math.floor(now.getTime() / 1000)
}

/**
 * 获取uuid
 * @returns
 */
function getTraceId() {
  const uuid = ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  )
  return uuid.replace(/-/g, '')
}

export default service
